#FILE: ZlateStrankyParser.py
#DESC: Parses Zlate Stranky content

import re

from web.service.LBCParser import LBCParser
from geo.models import NoSuchCity, NoSuchStreet, NoSuchLocation
from infra.logging import logger


class ZlateStrankyParser(LBCParser):

	def __init__(self, lbcategory, dataProcessor): 
		LBCParser.__init__(self, lbcategory, dataProcessor)
		
		self.orgName_ = None
		self.url_ = None
		self.phone_ = None
		self.email_ = None
		self.logo_ = None
		self.streetAddr_ = None
		self.cityAddr_ = None
		self.nextPage_ = None
		self.branchLinks_ = []
				
		self.inFnOrg_ = False
		self.inName_ = False
		self.inUrl_ = False
		self.inAddr_ = False
		self.inStreetAddr_ = False
		self.inCityAddr_ = False
		self.inPhone_ = False
		self.inNextPage_ = False
		self.inBranchLink_ = False
	
		log = logger.getLogger()
		log.debug("%s = %s" % (self, self.__dict__))
		
		
	def preParse(self):
		self.inNextPage_ = False
		self.nextPage_ = None
		del self.branchLinks_[1:]
		
		LBCParser.preParse(self)
		
		
	def reset__(self):
		self.url_ = False
		
		LBCParser.reset__(self)
		
		
	def start_td(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'vcard':
				self.inFnOrg_ = True
				break
			
			
	def end_td(self):
		log = logger.getLogger()
		
		if self.inFnOrg_ and self.orgName_:

			try:
				self.setCity(self.cityAddr_)
				self.setStreet(self.streetAddr_)
				self.createOrganization(name = self.orgName_, \
							            url = self.url_, \
							            phone = self.phone_, \
										logo = self.logo_, \
										email = self.email_)				
			except NoSuchCity, e:
				log.error('NoSuchCity exception caught, reason: %s' % e)
			except NoSuchStreet, e:
				log.error('NoSuchStreet exception caught, reason: %s' % e)			
			except NoSuchLocation, e:
				log.error('NoSuchStreet exception caught, reason: %s' % e)
			except Exception, e:
				log.error('An exception caught, reason: %s' % e)
		
			self.reset__()
			self.inFnOrg_ = False			
			
			
	def start_a(self, attrs):
		if self.inFnOrg_:
			for attr, value in attrs:
				if attr == 'href':
					if self.inName_: 
						self.url_ = self.dataProcessor_.getUrl(value)
						self.inUrl_ = True
					elif self.inBranchLink_:
						self.branchLinks_.append(self.dataProcessor_.getUrl(value))
					break
		elif self.inNextPage_:
			for attr, value in attrs:
				if attr == 'href':
					self.nextPage_ = self.dataProcessor_.getUrl(value)
					break
			
	
	def end_a(self):
		if self.inUrl_:
			self.inUrl_ = False


	def start_h2(self, attrs):
		if self.inFnOrg_:
			self.inName_ = True
			
			
	def end_h2(self):
		if self.inName_:
			self.inName_ = False


	def start_div(self, attrs):
		if self.inFnOrg_:
			for attr, value in attrs:
				if attr == 'class' and value == 'adr':
					self.inAddr_ = True
					break


	def end_div(self):
		if self.inAddr_:
			self.inAddr_ = False
			
			
	def start_span(self, attrs):
		if self.inAddr_:
			if attrs:
				for attr, value in attrs:
					if attr == 'class' and value == 'street-address':
						self.inStreetAddr_ = True
						break
			else:
				self.inCityAddr_ = True
		else:
			for attr, value in attrs:
				if attr == 'class' and value == 'folderLink':
					self.inBranchLink_ = True
					break


	def end_span(self):
		if self.inStreetAddr_:
			self.inStreetAddr_ = False
		if self.inCityAddr_:
			self.inCityAddr_ = False
		if self.inBranchLink_:
			self.inBranchLink_ = False
			
			
			
	def start_p(self, attrs):
		if self.inFnOrg_:
			for attr, value in attrs:
				if attr == 'class' and value == 'tel':
					self.inPhone_ = True
					break
		

	def end_p(self):
		if self.inPhone_:
			self.inPhone_ = False
			
			
	def start_li(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'nextLink':
				self.inNextPage_ = True 
				break
		
	
	def end_li(self):
		if self.inNextPage_:
			self.inNextPage_ = False	
	
					
	def do_handle_data(self, data):
		if self.inUrl_:
			if self.dataProcessor_.match(data):
				self.orgName_ = data
		elif self.inStreetAddr_:
			self.streetAddr_ = re.sub('[0-9]+\s*/', '', data)
		elif self.inCityAddr_:			
			self.cityAddr_ = data
		elif self.inPhone_:
			self.phone_ = data


	def hasNextPage(self):
		return self.nextPage_ != None


	def getNextPage(self):
		return self.nextPage_

			
	#
	# legacy code
	#
	
	'''
	def start_div(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'result-header':
				self.inHeader_ = True
				break


	def end_div(self):
		if self.inHeader_:
			self.inHeader_ = False


	def start_a(self, attrs):
		url = None
		for attr, value in attrs:
			if attr == 'href':
				if value.find('http') == -1:
					url = '%s%s' % (self.baseUrl_, value)
				else:
					url = value
				break
		if url:
			if self.inHeader_:
				self.url_ = url
			elif self.inNextPage_:
				self.nextPage_ = url
							
				
	def hasNextPage(self):
		return self.nextPage_ != None


	def getNextPage(self):
		return self.nextPage_


	def do_handle_data(self, data):
		log = logger.getLogger()		
		
		if self.inFamilyName_ or self.inFnOrg_:
			self.orgName_ = data
		if self.inStreetAddress_:
			self.streetAddr_ = data
		if self.inLocality_:
			try:
				self.setCity(data)
				self.setStreet(self.streetAddr_)
				if len(self.errors_) == 0:
					self.createOrganization(name = self.orgName_, \
								            url = self.url_, \
								            phone = self.phone_, \
											logo = self.logo_, \
											email = self.email_)				
			except NoSuchCity, e:
				log.error('NoSuchCity exception caught, reason: %s' % e)
			except NoSuchStreet, e:
				log.error('NoSuchStreet exception caught, reason: %s' % e)			
			except NoSuchLocation, e:
				log.error('NoSuchStreet exception caught, reason: %s' % e)
			except Exception, e:
				log.error('An exception caught, reason: %s' % e)
		
			self.reset__()
			
					

	def start_span(self, attrs):	
		for attr, value in attrs:
			if attr == 'class':
				if value == 'family-name':
					self.inFamilyName_ = True
				if value == 'street-address':
					self.inStreetAddress_ = True
				if value == 'locality':
					self.inLocality_ = True



	def end_span(self):
		if self.inFamilyName_:
			self.inFamilyName_ = False

		if self.inStreetAddress_:
			self.inStreetAddress_ = False
			
		if self.inLocality_:
			self.inLocality_ = False
			
			
	def start_h2(self, attrs):
		for attr, value in attrs:
			if attr == 'class':
				if value == 'fn org':
					self.inFnOrg_ = True	
					break
		
			
	def end_h2(self):
		if self.inFnOrg_:
			self.inFnOrg_ = False
			
	def start_li(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'next-page':
				self.inNextPage_ = True
				break
			
	
	def end_li(self):
		if self.inNextPage_:
			self.inNextPage_ = False
	'''		
			
	def getId(self):
		return self.__class__.__name__
		
	
	def getBranchLinks(self):
		return self.branchLinks_